<template>
  <div class="customer-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select v-model="searchForm.customerType" placeholder="请选择客户类型" clearable style="width: 180px">
            <el-option v-for="item in customerTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级">
          <el-select v-model="searchForm.grade" placeholder="请选择客户等级" clearable style="width: 180px">
            <el-option v-for="item in customerGradeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">新增客户</el-button>
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column prop="id" label="ID" width="80" align="center" /> -->
        <el-table-column prop="customerName" label="客户名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="customerType" label="客户类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getCustomerTypeTag(scope.row.customerType)">
              {{ getCustomerTypeLabel(scope.row.customerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="客户等级" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getCustomerGradeTag(scope.row.grade)">
              {{ getCustomerGradeLabel(scope.row.grade) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="historicalTotal" label="历史成交总额" width="140" align="right">
          <template #default="scope">
            <span>{{ formatCurrency(scope.row.historicalTotal) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" fixed="right">
          <template #default="scope">
            <el-button v-permission="['管理员', 'customer:update']" type="primary" link @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 客户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增客户' : '编辑客户'"
      width="600px"
      @close="resetForm"
    >
      <el-form ref="customerFormRef" :model="customerForm" :rules="customerFormRules" label-width="100px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="customerForm.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="customerForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="customerForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="customerForm.customerType" placeholder="请选择客户类型" style="width: 100%">
            <el-option v-for="item in customerTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级" prop="grade">
          <el-select v-model="customerForm.grade" placeholder="请选择客户等级" style="width: 100%">
            <el-option v-for="item in customerGradeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCustomerList, addCustomer, updateCustomer, deleteCustomers } from "@/api/customer";
import { getCustomerListExcel } from "@/api/export";

// 客户类型选项
const customerTypeOptions = [
  { value: 1, label: "个人", type: "info" },
  { value: 2, label: "企业", type: "success" },
  { value: 3, label: "政府", type: "warning" },
  { value: 4, label: "其他", type: "danger" },
];

// 客户等级选项
const customerGradeOptions = [
  { value: 1, label: "普通", type: "" },
  { value: 2, label: "银牌", type: "info" },
  { value: 3, label: "金牌", type: "warning" },
  { value: 4, label: "钻石", type: "success" },
];

// 搜索表单
const searchForm = reactive({
  customerName: "",
  phone: "",
  customerType: "",
  grade: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 对话框
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const customerFormRef = ref(null);
const customerForm = reactive({
  id: null,
  customerName: "",
  phone: "",
  address: "",
  customerType: 1,
  grade: 1,
});

// 表单验证规则
const customerFormRules = {
  customerName: [
    { required: true, message: "请输入客户名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号码格式不正确", trigger: "blur" },
  ],
  customerType: [{ required: true, message: "请选择客户类型", trigger: "change" }],
  grade: [{ required: true, message: "请选择客户等级", trigger: "change" }],
};

// 初始化
onMounted(() => {
  fetchCustomerList();
});

// 获取客户列表
const fetchCustomerList = async () => {
  loading.value = true;

  const response = await getCustomerList({
    ...searchForm,
    current: pagination.currentPage,
    size: pagination.pageSize,
  });

  if (response.success) {
    pagination.total = response.data.total;
    tableData.value = response.data.list;
  } else {
    // 错误消息已由request.js处理
    tableData.value = [];
    pagination.total = 0;
  }

  loading.value = false;
};

// 获取客户类型标签样式和文本
const getCustomerTypeTag = (type) => {
  const option = customerTypeOptions.find((item) => item.value === type);
  return option ? option.type : "";
};

const getCustomerTypeLabel = (type) => {
  const option = customerTypeOptions.find((item) => item.value === type);
  return option ? option.label : "未知类型";
};

// 获取客户等级标签样式和文本
const getCustomerGradeTag = (grade) => {
  const option = customerGradeOptions.find((item) => item.value === grade);
  return option ? option.type : "";
};

const getCustomerGradeLabel = (grade) => {
  const option = customerGradeOptions.find((item) => item.value === grade);
  return option ? option.label : "未知等级";
};

// 格式化货币
const formatCurrency = (value) => {
  if (value === undefined || value === null) return "¥0.00";
  return `¥ ${value.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
};

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchCustomerList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchCustomerList();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchCustomerList();
};

// 新增客户
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  resetForm();
};

// 编辑客户
const handleEdit = (row) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  Object.keys(customerForm).forEach((key) => {
    customerForm[key] = row[key];
  });
};

// 删除客户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户 "${row.customerName}" 吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteCustomers([row.id]);
    if (response.success) {
      ElMessage.success("删除成功");
      fetchCustomerList();
    }
    // 错误消息已由request.js处理
  } catch (error) {
    // 这里只处理用户取消操作
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的客户");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个客户吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteCustomers(selectedRows.value.map((row) => row.id));
    if (response.success) {
      ElMessage.success("批量删除成功");
      fetchCustomerList();
    }
    // 错误消息已由request.js处理
  } catch (error) {
    // 这里只处理用户取消操作
    if (error === "cancel") {
      ElMessage.info("已取消批量删除");
    }
  }
};

// 导出
const handleExport = async () => {
  try {
  await getCustomerListExcel();
    // 不需要显示消息，因为下载已经在函数内部处理了
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  }
};

// 提交表单
const submitForm = async () => {
  if (!customerFormRef.value) return;

  const valid = await customerFormRef.value.validate().catch(() => false);
  if (!valid) return;

  let response;
  if (dialogType.value === "add") {
    response = await addCustomer(customerForm);
  } else {
    response = await updateCustomer(customerForm);
  }

  if (response.success) {
    ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
    dialogVisible.value = false;
    fetchCustomerList();
  }
  // 错误消息已由request.js处理
};

// 重置表单
const resetForm = () => {
  if (customerFormRef.value) {
    customerFormRef.value.resetFields();
  }

  if (dialogType.value === "add") {
    Object.keys(customerForm).forEach((key) => {
      if (key === "customerType" || key === "grade") {
        customerForm[key] = 1;
      } else {
        customerForm[key] = "";
      }
    });
  }
};
</script>

<style scoped>
.customer-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 搜索过滤区样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

/* 表格区域 */
.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

:deep(.el-table__row td) {
  padding: 10px 0;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
}
</style>
